package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.dubbo.utils.DistanceUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class VideoService {

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private QuanZiService quanZiService;

    @DubboReference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    /**
     * 小视频上传
     *
     * @param picFile
     * @param videoFile
     * @return
     */
    public Object saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        try {
            Video video = new Video();
            video.setUserId(UserThreadLocal.get());
            //上传图片
            PicUploadResult uploadResult = this.picUploadService.upload(picFile);
            video.setPicUrl(uploadResult.getName());
            //上传视频
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true), null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            return this.videoApi.saveVideo(video);
        } catch (Exception e) {
            String msg = StrUtil.format("上传小视频失败! videoFile={},picFile={}",
                    videoFile.getOriginalFilename(), picFile.getOriginalFilename());
            log.error(msg, e);
        }
        return ErrorResult.builder().errCode("500").errMessage("上传小视频失败！").build();
    }

    /**
     * 小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        Long userId = UserThreadLocal.get();
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(userId, page, pageSize);
        List<Video> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        ArrayList<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            VideoVo videoVo = BeanUtil.toBeanIgnoreError(record, VideoVo.class);
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setCover(record.getPicUrl());
            UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(UserThreadLocal.get());
            UserLocationVo publishUserLocationVo = this.userLocationApi.queryByUserId(videoVo.getUserId());
            //计算距离
            if (ObjectUtil.isEmpty(userLocationVo)) {
                return null;
            }
            Map<String, Object> map = DistanceUtil.getDistance(userLocationVo.getLongitude(), userLocationVo.getLatitude(),
                    publishUserLocationVo.getLongitude(), publishUserLocationVo.getLatitude());
            videoVo.setSignature(map.get("distance") + "km  " + publishUserLocationVo.getAddress());
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//点赞数
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(UserThreadLocal.get(), videoVo.getId()) ? 1 : 0);//是否点赞（1是，0否）
            videoVo.setHasFocus(this.videoApi.isFollowUser(UserThreadLocal.get(), videoVo.getUserId()) ? 1 : 0);//是否关注（1是，0否）
            videoVo.setCommentCount(this.quanZiApi.queryCommentCount(videoVo.getId()));//评论数
            videoVo.setId(record.getId().toHexString());
            videoVoList.add(videoVo);
        }
        //查询用户信息
        List<Object> userIdList = CollUtil.getFieldValues(videoVoList, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        for (VideoVo videoVo : videoVoList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(videoVo.getUserId(), userInfo.getUserId())) {
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
        }
        pageResult.setCounts(videoVoList.size());
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 视频点赞
     *
     * @param videoId 视频id
     * @return
     */
    public Long likeComment(String videoId) {
        Long userId = UserThreadLocal.get();
        Boolean flag = this.quanZiApi.likeComment(userId, videoId);
        if (flag) {
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 视频取消点赞
     *
     * @param videoId 视频id
     * @return
     */
    public Long disLikeComment(String videoId) {
        Long userId = UserThreadLocal.get();
        Boolean flag = this.quanZiApi.disLikeComment(userId, videoId);
        if (flag) {
            return this.quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    /**
     * 评论列表
     */
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
        return this.quanZiService.queryCommentList(videoId, page, pageSize);
    }

    /**
     * 提交评论
     *
     * @param videoId
     * @return
     */
    public Boolean saveComment(String videoId, String content) {
        return this.quanZiService.saveComments(videoId, content);
    }

    /**
     * 关注
     *
     * @param userId
     * @return
     */
    public Boolean followUser(Long userId) {
        return this.videoApi.followUser(UserThreadLocal.get(), userId);
    }

    /**
     * 取消关注
     *
     * @param userId
     * @return
     */
    public Boolean disFollowUser(Long userId) {
        return this.videoApi.disFollowUser(UserThreadLocal.get(), userId);
    }

}
